import { ref, onBeforeMount, reactive, getCurrentInstance } from 'vue'
import { onLaunch, onShow, onHide, onShareAppMessage, onShareTimeline, onPageScroll } from "@dcloudio/uni-app";
import { componentsStore } from '@/store/modules/components'
import { get_, set_, clear_ } from '@/utils'
import server from '@/apiData/api';


const setNum = ref<number>(0);
/**
   @param {
    name:'getNotice',//在server里的接口名称
    title:'通知公告',//接口名，提示信息用
    noMsg:false,//是否不需要提示
    param:[],//参数，数组对象
    isRoot:false,//兼容接口没有返回code字段，直接返回数据的或跳过code判断需自己显示错误提示等情况(一般配合allBack:true使用)
    unLoading:Boolean，//是否显示loading效果
    allBack:false,//返回所有数据
  }
  */
export function setApiData() {
  const { proxy }: any = getCurrentInstance()
  const store = componentsStore()
  const setApi = async (obj: any) => {

    let data: any = reactive({
      code: 500,
      msg: ''
    })
    try {
      if (!obj.unLoading) {
        store.loadingFn_(true)
        setNum.value++
      }
      const param = obj.param || []
      const result = await server[obj.name](...param)

      if (result.code === 200 || obj.isRoot) {
        let code: any = {}
        code = {
          code: 200
        }
        data = {
          ...code,
          ...result
        }
      } else {
        console.error(obj.title + " 请求出错", result.code, result.msg)
        data = {
          msg: result.msg,
          code: 500
        }

      }

    } catch (e) {
      console.error(obj.title + " 请求失败", e + "", e)

      proxy.showMsg.show({ text: obj.title })
    }
    if (!obj.unLoading) {
      setNum.value--;
      if (setNum.value === 0) {
        store.loadingFn_(false)
      }
    }
    // console.log(data, 'data')
    return data;

  }
  return { setApi }
}
/**
 * @params {Function} fn  需要防抖的函数 delay 防抖时间
 * @returns {Function} debounce 防抖函数
 * @example  
 * const { debounce } = useDebounce()
 * const fn = () => { console.log('防抖') }
 * const debounceFn = debounce(fn, 1000)
 * debounceFn()
 */
export function useDebounce() {
  const debounce = (fn, delay) => {
    // console.log(fn, delay)
    let timer = null;
    return function () {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, delay);
    };
  };
  return { debounce };
}
/**
* @params {Function} fn  需要节流的函数 delay 节流时间
* @returns {Function} throttle 节流函数
* @example
* const { throttle } = useThrottle()
* const fn = () => { console.log('节流') }
* const throttleFn = throttle(fn, 1000)
* throttleFn()
*  */
export function useThrottle() {
  const throttle = (fn, delay) => {
    let timer = null;
    return function () {
      if (!timer) {
        timer = setTimeout(() => {
          fn.apply(this, arguments);
          timer = null;
        }, delay);
      }
    };
  };

  return { throttle };
}
/**
 *  倒计时
 *  @param {Number} second 倒计时秒数
 *  @return {Number} count 倒计时秒数
 *  @return {Function} countDown 倒计时函数
 *  @example
 *  const { count, countDown } = useCountDown()
 *  countDown(60)
 * <view>{{ count }}</view>
 */
export function useCountDown() {
  const count = ref(0);
  const timer = ref(null);
  const countDown = (second, ck) => {
    if (count.value === 0 && timer.value === null) {
      ck();
      count.value = second;
      timer.value = setInterval(() => {
        count.value--;
        if (count.value === 0) clearInterval(timer.value);
      }, 1000);
    }
  };
  onBeforeMount(() => {
    timer.value && clearInterval(timer.value);
  });
  return {
    count,
    countDown,
  };
}
/**
 * 获取随机字符串
 @param{
  
 }
 */
export function random_() {
  const randomValue: any = ref('')
  const randomString = (length) => {
    const randomStr = ref<string>("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    for (var i = length; i > 0; --i) randomValue.value += randomStr.value[Math.floor(Math.random() * randomStr.value.length)];
  }
  return { randomString, randomValue }
}

export function Money() {
  const ObjectMoney = (Node) => {
    if (Node) {
      let opt = Node.split('.')
      if (opt.length == 1) {
        opt.push('00')
        return opt
      } else {
        return opt
      }
    } else {
      return ['0', '00']
    }
  }
  return { ObjectMoney }
}
export function sharefn() {
  // onShow((res) => {
  //   uni.showShareMenu({
  //     withShareTicket: true,
  //     menus: ["shareAppMessage", "shareTimeline"],
  //   })
  // })
  const shareList = reactive({
    title: '开心桃小程序',
    path: '/pages/index/index',
    imageUrl: '',
    desc: '',
    content: ''
  })
  onShareAppMessage((res) => {
    return {
      title: shareList.title,
      path: shareList.path,
      imageUrl: shareList.imageUrl
    }
  })
  onShareTimeline(() => {
    return {
      title: shareList.title,
      path: '/pages/index/index',
      imageUrl: '',
      desc: '',
      content: ''
    }

  })
  return {
    shareList
  }
}
export function Scroll() {
  const top = ref<any>('')
  onPageScroll((e) => {
    // console.log(e, 'hooks')
    top.value = e
  })
  return { top }
}
export function UploadImg() {
  const { proxy }: any = getCurrentInstance()


  const uloadImg_ = (() => {


    return new Promise((resolve, reject) => {
      const url_ = get_('APIHTTPS') + 'mall/file/upload.json'
      const token = get_('Token')
      const obj = {
        code: 500,
        msg: '图片上传出错...'
      }
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: function (res) {
          let filePath = res.tempFiles[0].path;
          let filename = filePath.substr(filePath.lastIndexOf('/') + 1);
          uni.uploadFile({
            url: url_, //后台地址
            filePath: filePath,
            name: 'file',
            fileType: 'image',
            header: {
              'token': token,
            },
            formData: {
              'image': filePath
            },
            success: (res) => {
              let data = JSON.parse(res.data)
              if (data.code == 200) {
                let obj = {
                  code: 200,
                  imageUrl: '',
                  filename: filename
                }
                data && data.data ? obj.imageUrl = data.data : obj
                resolve(obj)
              } else {
                proxy.showMsg.show({ text: obj.msg })
                resolve(obj)
              }
            },
            fail: (error) => {
              reject(error)
            }
          })
        },
        fail: err => {
          // console.log(err, 'rrrrrrrrrrr')
        }
      });
    })
  })
  return { uloadImg_ }
}

export function Uploadvideo() {
  const { proxy }: any = getCurrentInstance()
  const Uploadvideofile = (() => {


    return new Promise((resolve, reject) => {
      const url_ = get_('APIHTTPS') + 'mall/file/upload.json'
      const token = get_('Token')
      const obj = {
        code: 500,
        msg: '上传出错...'
      }
      // #ifdef MP-WEIXIN ||  MP-TOUTIAO
      uni.showLoading({
        title: '加载中...'
      })
      uni.chooseMedia({
        count: 1,
        mediaType: ['video'],
        sourceType: ['album', 'camera'], //从相册选择
        sizeType: ['original', 'compressed'],
        maxDuration: 30,
        success: function (res) {
          // console.log(res, 'res')
          let filePath = res.tempFiles[0].tempFilePath;
          let f_ = filePath.split('.')
          let filename = 'video_' + new Date().getTime() + '.' + f_[1];
          uni.uploadFile({
            url: url_, //后台地址
            filePath: filePath,
            name: 'file',
            fileType: 'video',
            header: {
              'token': token,
            },
            formData: {
              'file': filePath
            },
            success: (res) => {
              let data = JSON.parse(res.data)
              if (data.code == 200) {
                let obj = {
                  code: 200,
                  imageUrl: '',
                  filename: filename
                }
                data && data.data ? obj.imageUrl = data.data : obj
                resolve(obj)
              } else {
                proxy.showMsg.show({ text: obj.msg })
                resolve(obj)
              }
              uni.hideLoading()
              // uni.$emit("showLoading", false);
            },
            fail: (error) => {
              // uni.$emit("showLoading", false);
              uni.hideLoading()
              console.log(error, 'error')
              reject(error)
            }
          })
        },
        fail: err => {
          uni.hideLoading()
        }
      });
      // #endif
      // #ifdef H5
      uni.$emit("showLoading", true);
      uni.chooseFile({
        count: 1,
        type: 'video',
        extension: ['.m4a', '.mp3'],
        // extension: ['.mp3', '.mp4'], //可以指定是原图还是压缩图，默认二者都有
        success: function (res) {
          // console.log(res, 'res')
          let filePath = res.tempFiles[0].path;
          let filename = res.tempFiles[0].name;
          uni.uploadFile({
            url: url_, //后台地址
            filePath: filePath,
            name: 'file',
            fileType: 'video',
            header: {
              'token': token,
            },
            formData: {
              'file': filePath
            },
            success: (res) => {
              let data = JSON.parse(res.data)
              if (data.code == 200) {
                let obj = {
                  code: 200,
                  imageUrl: '',
                  filename: filename
                }
                data && data.data ? obj.imageUrl = data.data : obj
                resolve(obj)
              } else {
                proxy.showMsg.show({ text: obj.msg })
                resolve(obj)
              }
              uni.$emit("showLoading", false);

            },
            fail: (error) => {
              uni.$emit("showLoading", false);
              // console.log(error, 'error')
              reject(error)
            }
          })
        },
        fail: (err) => {
          // console.log(err, 'eeee')
          uni.$emit("showLoading", false);
          uni.hideLoading()
        },
        complete: (node) => {
          // console.log(node, 'node')
        }
      });
      setTimeout(() => {
        uni.$emit("showLoading", false);
      }, 5000)
      uni.hideLoading()
      // #endif
    })
  })
  return { Uploadvideofile }
}


export function UpNewloadImg() {
  const { proxy }: any = getCurrentInstance()
  const filePath = ref<string>('')
  const uloadImg_ = (() => {
    return new Promise((resolve, reject) => {
      const url_ = get_('APIHTTPS') + 'mall/file/upload.json'
      const token = get_('Token')
      const obj = {
        code: 500,
        msg: '图片上传出错...'
      }

      uni.uploadFile({
        url: url_, //后台地址
        filePath: filePath.value,
        name: 'file',
        fileType: 'image',
        header: {
          'token': token,
        },
        success: (res) => {
          let data = JSON.parse(res.data)
          if (data.code == 200) {
            let obj = {
              code: 200,
              imageUrl: '',

            }
            data && data.data ? obj.imageUrl = data.data : obj
            uni.$emit("showLoading", false);
            resolve(obj)
          } else {
            uni.$emit("showLoading", false);
            proxy.showMsg.show({ text: obj.msg })
            resolve(obj)
          }
        },
        fail: (error) => {
          uni.$emit("showLoading", false);
          console.log(error, 'error')
          reject(error)
        }
      })
    })
  })
  return { uloadImg_, filePath }
}



export function chooseAll() {
  const { proxy }: any = getCurrentInstance()
  const chooseAllFile_ = (() => {

    // uni.$emit("showLoading", true);
    return new Promise((resolve, reject) => {
      const url_ = get_('APIHTTPS') + 'mall/file/upload.json'
      const token = get_('Token')
      const obj = {
        code: 500,
        msg: '文件上传...'
      }
      // chooseMessageFile
      // chooseFile
      // #ifdef MP-WEIXIN  || MP-TOUTIAO
      uni.showLoading({
        title: '加载中',
      })
      uni.chooseMedia({
        count: 1,
        mediaType: ['image', 'video'],
        sourceType: ['album', 'camera'], //从相册选择
        sizeType: ['original', 'compressed'],
        maxDuration: 30,
        success: function (res) {
          let filePath = res.tempFiles[0].tempFilePath;
          let filename = filePath.substr(filePath.lastIndexOf('/') + 1);
          uni.uploadFile({
            url: url_, //后台地址
            filePath: filePath,
            name: 'file',
            fileType: 'video',
            header: {
              'token': token,
            },
            // formData: {
            //   'file': filePath
            // },
            success: (res) => {
              let data = JSON.parse(res.data)
              if (data.code == 200) {
                let obj = {
                  code: 200,
                  imageUrl: '',
                  filename: filename
                }
                data && data.data ? obj.imageUrl = data.data : obj
                resolve(obj)
              } else {
                proxy.showMsg.show({ text: obj.msg })
                resolve(obj)
              }
              // uni.$emit("showLoading", false);
              uni.hideLoading()

            },
            fail: (error) => {
              // uni.$emit("showLoading", false);
              uni.hideLoading()
              proxy.showMsg.show({ text: '上传失败....' })
              console.log(error, 'error')
              reject(error)
            }
          })
        },
        fail: e => {
          console.log(e, 'e')
          // uni.$emit("showLoading", false);
          uni.hideLoading()
        }
      });

      // #endif
      // #ifdef H5
      // uni.$emit('showLoading', true)
      uni.chooseFile({
        type: 'all',
        count: 1,
        sourceType: ['album', 'camera'], //从相册选择
        sizeType: ['original', 'compressed'],
        success: function (res) {
          let filePath = res.tempFiles[0].path;
          let filename = res.tempFiles[0].name.substr(res.tempFiles[0].name.lastIndexOf('/') + 1);
          uni.uploadFile({
            url: url_, //后台地址
            filePath: filePath,
            name: 'file',
            fileType: 'video',
            header: {
              'token': token,
            },
            formData: {
              'file': filePath
            },
            success: (res) => {
              let data = JSON.parse(res.data)
              if (data.code == 200) {
                let obj = {
                  code: 200,
                  imageUrl: '',
                  filename: filename
                }
                data && data.data ? obj.imageUrl = data.data : obj
                resolve(obj)
              } else {
                proxy.showMsg.show({ text: obj.msg })
                resolve(obj)
              }
              uni.$emit('showLoading', false)
            },
            fail: async (error) => {
              uni.$emit('showLoading', false)
              reject(error)
            }
          })
        },
        fail: (err) => {
          console.log(err, 'errr')
        }

      });
      console.log(11111)
      // #endif
    })
  })
  return { chooseAllFile_ }
}
export function uploadFileVideo() {
  const { proxy }: any = getCurrentInstance()
  const downloadUrl = ref<any>('')
  const downloadID = ref<string | number>('')
  let downloadObj: any = {}
  const downloadFile_ = (() => {
    uni.$emit("showLoading", true);
    return new Promise((resolve, reject) => {

      const token = get_('Token')
      let obj = {
        code: 500,
        msg: '视频下载...'
      }
      // #ifdef MP-WEIXIN || MP-TOUTIAO
      downloadObj = uni.downloadFile({
        url: downloadUrl.value,
        // filePath: '/text',
        success: e => {
          console.log(e, 'e')
          if (e.tempFilePath) {
            uni.saveVideoToPhotosAlbum({
              filePath: e.tempFilePath,
              success: res => {
                let obj = {
                  code: 200,
                }
                uni.$emit("showLoading", false);
                proxy.showMsg.show({ text: '视频下载成功' })
              },
              fail: err => {
                console.log(err, 'eeeee')
                console.log(err, 'ee')
                let obj = {
                  code: 500,
                  msg: '视频下载出错...'
                }
                proxy.showMsg.show({ text: obj.msg })
                uni.$emit("showLoading", false);
                reject(obj)
              }
            })
          }
        }
      })
      downloadObj.onProgressUpdate((res) => {
        console.log(res, 'res')
        console.log('下载进度' + res.progress);
        console.log('已经下载的数据长度' + res.totalBytesWritten);
        console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
        resolve(res.totalBytesWritten)
      })
      // #endif
      // #ifdef H5
      // server.download({ id: downloadID.value }).then((e) => {
      //   console.log(e, 'e')
      //   let blob = new Blob([e], { type: 'video/mp4' })
      //   console.log(blob, 'blob')
      //   let link = document.createElement('a')
      //   link.download = 'video';
      //   link.href = URL.createObjectURL(blob);
      //   link.click()
      // })
      const ua = navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        // 在微信中打开
        const url = document.location.toString()
        const url_new = url.split('#')
        const url_ = url_new[0] + '#/pages/user/index' + '?Token=' + get_('Token')
        window.location.href = url_
        server.download({ id: downloadID.value }).then((e) => {
          let blob = new Blob([e], { type: 'video/mp4' })
          let link = document.createElement('a')
          link.download = 'video_' + new Date();
          link.href = URL.createObjectURL(blob);
          link.click()
        })
        proxy.showMsg.show({ text: '请打开普通浏览器下载....' })
      } else {
        let a = document.createElement('a');
        a.href = downloadUrl.value;
        a.download = "video_" + new Date().getDate().toString();
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(downloadUrl.value);
        document.body.removeChild(a);
      }
      uni.$emit("showLoading", false);
      // #endif
    })
  })
  return { downloadUrl, downloadFile_, downloadID }
}

export function creareAdunit() {
  const { proxy }: any = getCurrentInstance()
  const adunitValue = ref<any>(null)
  const successValue = ref<any>(null)
  const creareAdunit_ = (() => {
    adunitValue.value = tt.createRewardedVideoAd({ adUnitId: "wsoqa07kpibcj3oidy" });
    console.log(adunitValue.value, '2222')
  })
  const showVideoAd = (() => {   // 广告显示
    // 绑定事件监听
    bindListener();
    // 显示广告
    adunitValue.value
      .show()
      .then(() => {
        console.log("广告显示成功");
      })
      .catch((err) => {
        console.log("广告组件出现问题", err);
        // 可以手动加载一次
        adunitValue.value.load().then(() => {
          console.log("手动加载成功");
          // 加载成功后需要再显示广告
          return adunitValue.value.show();
        });
      });
  })
  const bindListener = (() => {
    adunitValue.value.onLoad(() => {
      console.log("拉取广告素材成功");
    });

    adunitValue.value.onClose((res) => {
      successValue.value = res
      if (res.isEnded) {
        // 给予奖励
      };
    });
    adunitValue.value.onError(error => {
      console.log("errorCode: " + error.code);
      console.log("errMsg: " + error.errMsg);
    });
  })
  return { creareAdunit_, showVideoAd, successValue }
}